# 加密服务（用于密码管理器）
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
import os

class CryptoService:
    """加密服务类 - 使用AES-256加密"""
    
    @staticmethod
    def generate_salt():
        """生成随机盐值"""
        return base64.urlsafe_b64encode(os.urandom(16)).decode('utf-8')
    
    @staticmethod
    def derive_key(master_password: str, salt: str) -> bytes:
        """从主密码派生加密密钥
        
        Args:
            master_password: 主密码
            salt: 盐值
            
        Returns:
            派生的密钥
        """
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt.encode('utf-8'),
            iterations=100000,
        )
        key = base64.urlsafe_b64encode(kdf.derive(master_password.encode('utf-8')))
        return key
    
    @staticmethod
    def hash_password(password: str, salt: str) -> str:
        """哈希密码（用于验证主密码）
        
        Args:
            password: 密码
            salt: 盐值
            
        Returns:
            密码哈希值
        """
        key = CryptoService.derive_key(password, salt)
        return base64.urlsafe_b64encode(key).decode('utf-8')
    
    @staticmethod
    def encrypt(plaintext: str, master_password: str, salt: str) -> str:
        """加密文本
        
        Args:
            plaintext: 明文
            master_password: 主密码
            salt: 盐值
            
        Returns:
            加密后的文本
        """
        key = CryptoService.derive_key(master_password, salt)
        fernet = Fernet(key)
        encrypted = fernet.encrypt(plaintext.encode('utf-8'))
        return encrypted.decode('utf-8')
    
    @staticmethod
    def decrypt(ciphertext: str, master_password: str, salt: str) -> str:
        """解密文本
        
        Args:
            ciphertext: 密文
            master_password: 主密码
            salt: 盐值
            
        Returns:
            解密后的文本
        """
        try:
            key = CryptoService.derive_key(master_password, salt)
            fernet = Fernet(key)
            decrypted = fernet.decrypt(ciphertext.encode('utf-8'))
            return decrypted.decode('utf-8')
        except Exception as e:
            raise ValueError('解密失败，主密码可能不正确')
    
    @staticmethod
    def check_password_strength(password: str) -> dict:
        """检测密码强度
        
        Args:
            password: 密码
            
        Returns:
            包含强度等级和建议的字典
        """
        score = 0
        suggestions = []
        
        if len(password) >= 8:
            score += 1
        else:
            suggestions.append('至少8个字符')
        
        if len(password) >= 12:
            score += 1
        
        if any(c.islower() for c in password) and any(c.isupper() for c in password):
            score += 1
        else:
            suggestions.append('包含大小写字母')
        
        if any(c.isdigit() for c in password):
            score += 1
        else:
            suggestions.append('包含数字')
        
        if any(c in '!@#$%^&*()_+-=[]{}|;:,.<>?' for c in password):
            score += 1
        else:
            suggestions.append('包含特殊字符')
        
        if score <= 2:
            level = '弱'
            color = 'danger'
        elif score <= 3:
            level = '中'
            color = 'warning'
        else:
            level = '强'
            color = 'success'
        
        return {
            'level': level,
            'color': color,
            'score': score,
            'suggestions': suggestions
        }

